<script setup lang="ts">
import { useChannelStore } from '@/stores/channel';
import type { ArticleItem, ArticleResData } from '@/types';
import axios from 'axios';
import { ref } from 'vue';
import { watch } from 'vue';
import { useRouter } from 'vue-router';
const router = useRouter()
const store = useChannelStore()


// 2. 监听频道id的变化, 去获取数据
const listArr = ref<ArticleItem[]>([])
watch(() => store.channelId, async () => {
  const res = await axios.get<ArticleResData>('http://geek.itheima.net/v1_0/articles', {
    params: {
      channel_id: store.channelId,
      timestamp: Date.now()
    }
  })
  listArr.value = res.data.data.results
}, {
  immediate: true
})


// 1. 跳转到详情页
const gotoDetail = (id: string) => {
  router.push({
    path: '/detail',
    query: { id }
  })
}
</script>

<template>
  <div class="article-list">
    <div class="article-item" v-for="item in listArr" :key="item.art_id" @click="gotoDetail(item.art_id)">
      <p class="title">{{ item.title }}</p>
      <img v-for="(img, index) in item.cover.images" :key="index" class="img" :src="img" alt="">
      <div class="info">
        <span>{{ item.aut_name }}</span>
        <span>{{ item.comm_count }}评论</span>
        <span>{{ item.pubdate }}</span>
      </div>
    </div>
  </div>
</template>